import axios, { type AxiosResponse } from "axios"
import qs from "qs"
import cookie from "js-cookie"
import router from "@/router"
import { ElMessage } from "element-plus";

import NProgress from 'nprogress'
import { useUserStore } from "@/stores/admin";
declare interface TypeResponse extends AxiosResponse {
    /**
     * 错误号，200表示成功，10006令牌过期
     */
    errno: number,
    /**
     * 返回的信息
     */
    errmsg: string
    /**
     * 图片路径
     */
    url: string
}

let baseURL = "";
if (process.env.NODE_ENV === "development") {
    baseURL = "/m.api";
} else {
    baseURL = "http://zxwyit.cn:8989/m.api";
}

const instance = axios.create({
    baseURL,
    timeout: 6000,
    headers: { 'content-type': 'application/x-www-form-urlencoded' }
})

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    if (config.headers) {
        config.headers['AdminToken'] = cookie.get("token") + "";
        NProgress.start()
    }
    return config
})

// 添加响应拦截器
const METHOD_TYPE = ['_mt=edit', '_mt=create', '_mt=delete','_mt=update']
instance.interceptors.response.use(async response => {
    let data = response.data;
    let { errno, errmsg } = data;
    let path = router.currentRoute.value.fullPath;
    console.log(response.config.data)
    if (10006 === errno) {
        const configData = response.config.data || "";
        let index = METHOD_TYPE.findIndex((item) => configData.includes(item));
        if (-1 == index) {
            ElMessage.error(errmsg);
            router.replace({ path: "/login", query: { back: path } }); //登录后跳回原来的地址
            return;
        } else {
            const store = useUserStore();
            const { username, password } = store.userInfo;
            let loginData = { _gp: "admin", _mt: "login", username, password };
            const { errmsg, errno, data } = await post(loginData);
            if (200 == errno) {
                // 获取当前时间
                let now = new Date()
                // 在本地时间的基础上添加30分钟
                now.setTime(now.getTime()+1000*60*30)
                // 使用cookir进行限时存储token，添加计时，固定时间后清除token
                cookie.set("token",data,{expires:now})
            } else {
                ElMessage.error(errmsg);
            }
            const headersData = response.config.headers || {};
            headersData.AdminToken = data;
            let res = await axios.request(response.config);
            return res.data
        }
    }
    NProgress.done()
    return data
}, function (error) {
    return Promise.reject(error)
})

// 封装两大请求
// get
function get(params?: object): Promise<TypeResponse> {
    return instance.get("", { params })
}
// post
function post(data: object, params?: object): Promise<TypeResponse> {
    return instance.post("", qs.stringify(data), { params })
}

// 富文本图片请求
export function upload(data:object): Promise<TypeResponse> {
    return instance.post("../upload/admin", data);
}

// 暴露
export {
    get,
    post
}